<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <Search :allOpts="formInline.allOpts" v-model="formInline.cOpts" @blur="search"></Search>
        </el-form-item>
        <el-form-item>
          <el-button type="info" :disabled="butStatus.selectNum" @click="zdxq">字段详情</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" :disabled="butStatus.selectNums" @click="fqxq">分区详情</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="info" :disabled="butStatus.selectNum" @click="jbyj">建表语句</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="dialogFormVisible = true">新建表</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="jzsj">加载数据</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="deleteTable" :disabled="butStatus.selectNum">删除</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--数据列表-->
    <el-table :data="tableData"
              border
              style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="hive_database_name" label="数据库" width="120"></el-table-column>
      <el-table-column prop="table" label="表"></el-table-column>
      <el-table-column label="分区数">
        <template scope="scope">
          <span>{{scope.row.partitions_num | partNum}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="files_num" label="文件数"></el-table-column>
      <el-table-column prop="files_sizes" label="容量(B)"></el-table-column>
    </el-table>

    <!--分页-->
    <el-col :span="24" class="toolbar" style="padding-bottom:10px;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.start_index"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pagination.page_count"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.count"
        style="float:right"></el-pagination>
    </el-col>
    <!--编辑界面-->
    <el-dialog title="建表语句" v-model="dialogFormVisible" @close="resetForm">
      <div class="form-warn">
        <el-form :model="form" ref="form" :rules="editFormRules">
          <!--<el-form-item label="租户" prop="tenant_id" :label-width="formLabelWidth">
              <el-select v-model="form.tenant_id" placeholder="请选择">
                  <el-option v-for="item in getTenants" :label="item.tenant_name"
                             :value="item.tenant_id"></el-option>
              </el-select>
          </el-form-item>-->
          <el-form-item label="SQL" prop="createtablestr" :label-width="formLabelWidth">
            <el-input v-model="form.createtablestr" type="textarea"
                      :autosize="{ minRows: 4, maxRows: 8 }"
                      placeholder="输入的必须是建表语句SQL"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="createTableByCreateStr" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>

    <el-dialog title="加载数据" v-model="dialogFormData" size="tiny" @close="resetForm">
      <div class="form-warn">
        <el-form :model="formUp" :rules="editFormRules" ref="formUp" :label-width="formLabelWidth">
          <el-form-item label="数据库" prop="dbs">
            <el-select v-model="formUp.dbs" placeholder="请选择" style="width: 100%;">
              <el-option v-for="(item,start_index) in tenant_hive1" :label="item.hive_database_name"
                         :value="item.hive_database_name" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表" prop="table">
            <el-input v-model="formUp.table" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="文件" prop="properties_files">
            <UploadPath v-model="formUp.properties_files" uploadType="1"></UploadPath>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">{{btnEditText}}</el-button>
      </div>
    </el-dialog>
    <!--弹框展示-->
    <el-dialog title="字段详情" v-model="butStatus.fieldDetails">
      <el-table :data="fieldDetailsData">
        <el-table-column property="column_name" label="字段"></el-table-column>
        <el-table-column property="type_name" label="类型"></el-table-column>
        <el-table-column property="comment" label="说明"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="butStatus.fieldDetails = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="分区详情" v-model="butStatus.fqxqDetails">
      <el-table :data="fqxqDetailsData">
        <el-table-column property="part_name" label="分区"></el-table-column>
        <el-table-column property="location" label="地址"></el-table-column>
        <el-table-column property="num" label="文件数"></el-table-column>
        <el-table-column property="file_size" label="容量(B)"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="butStatus.fqxqDetails = false">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="建表语句" v-model="butStatus.jbyjDetails">
      <el-input
        type="textarea"
        :autosize="{ minRows: 4, maxRows: 10}"
        placeholder="请输入SQL建表语句"
        v-model="jbyjDetailsData"
        :disabled="true">
      </el-input>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="butStatus.jbyjDetails = false">确 定</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
  import util from '../../common/util'
  import UploadPath from '../../components/UploadPath.vue'
  import Search from '../../components/Search.vue'
  import dao from '../../common/dao'
  import { mapGetters } from 'vuex'

  import NProgress from 'nprogress'
  export default {
    components: {UploadPath, Search},
    computed: {
      ...mapGetters([
        'getTenants'
      ])
    },
    data () {
      return {
        multipleSelection: [],
        btnEditText: "确定",
        formLabelWidth: "120px",
        form: {
          tenant_id: "",
          createtablestr: ""
        },
        formUp: {
          dbs: '',
          table: '',
          properties_files: ''
        },
        dialogFormData: false,
        dialogFormVisible: false,
        fieldDetailsData: [],
        fqxqDetailsData: [],
        jbyjDetailsData: '',
        butStatus: {
          selectNum: true,
          selectNums: true,
          fieldDetails: false,
          fqxqDetails: false,
          jbyjDetails: false,
        },
        timeout: null,
        formInline: {
          allOpts: [{
            key: 'hive_database_name',
            label: '数据库',
            type: '',
            val: ''
          }, {
            key: 'table',
            label: '表',
            type: '',
            val: ''
          }],
          cOpts: [{
            key: 'hive_database_name',
            label: '数据库',
            type: '',
            val: ''
          }]
        },
        tableData: [],
        pagination: {
          count: 0,
          page_count: 20,
          start_index: 1
        },
        tenant_hive: [],
        tenant_hive1: [],
        editFormRules: {
          tenant_id: [
            {required: true, message: '请选择租户！', trigger: 'change'},
          ],
          createtablestr: [
            {required: true, message: '请输入标准的建表语句！', trigger: 'blur'},
          ],
          dbs: [
            {required: true, message: '请选择数据库！', trigger: 'change'},
          ],
          table: [
            {required: true, message: '请输入表！', trigger: 'blur'},
            {validator: this.checkLoadHdfsFileToHive, trigger: 'blur'}
          ],
          properties_files: [
            {required: true, message: '请选择文件！', trigger: 'blur'},
            {validator: (rule, value, callback)=>{
              if(/\/[\w]+\.[\w]+$/.test(value)){
                callback()
              } else {
                callback(new Error('只能选择文件'))
              }
            }, trigger: 'blur'},
          ]
        },
      }
    },
    methods: {
      search(val){
        //调用查询服务
        this.getTableData();
      },
      /*加载数据页面确定按钮*/
      editSubmit () {
        let hive_database_name = this.formUp.dbs
        let table = this.formUp.table
        let hdfs_path = this.formUp.properties_files
        this.$refs.formUp.validate( (valid) => {
          if (!valid) {return false}
          dao.loadHdfsFileToHive({hive_database_name, table, hdfs_path}).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.dialogFormData = false;
            this.formUp.dbs = ''
            this.formUp.table = ''
            this.formUp.properties_files = ''
            this.$message('加载数据成功');
          })
        })
      },
      /*字段详情*/
      zdxq () {
        this.butStatus.fieldDetails = true;
        this.getTableColumnsInfo();
      },
      /*分区详情*/
      fqxq () {
        this.butStatus.fqxqDetails = true;
        this.getTablePartitionsInfo()
      },
      /*建表语句*/
      jbyj () {
        this.butStatus.jbyjDetails = true;
        this.getTableCreateTable()
      },
      /*加载数据*/
      jzsj () {
        this.dialogFormData = true
        this.getHiveList()
      },
      handleSelectionChange (val) {

        if (val.length == 1) {
          this.butStatus.selectNum = false;
          if(val[0].partitions_num != "-1") this.butStatus.selectNums = false;
          if(val[0].partitions_num == 0) this.butStatus.selectNums = true;
        } else {
          this.butStatus.selectNum = true;
          this.butStatus.selectNums = true;
        }
        this.multipleSelection = val;
      },
      sizeChange () {

      },
      checkLoadHdfsFileToHive (rule, value, callback) {
        clearTimeout(this.timeout);
        if (this.formUp.dbs == '') {
          callback(new Error('先选择数据库'));
          return false
        }
        this.timeout = setTimeout(() => {
          let hive_database_name = this.formUp.dbs
          let table = this.formUp.table
          if (hive_database_name == '') {
            callback(new Error('先选择数据库'))
            return false
          }
          dao.checkLoadHdfsFileToHive({hive_database_name, table}).then(res => {
            if (res.FX.err) {
              callback()
              return false
            }
            if (res.body.isExist == 'exist') callback()
            else callback(new Error('不存在该表'))
          })
        }, 3000 * Math.random());
      },
      getHiveList(){
        dao.getHiveList({}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false
          }
          this.tenant_hive1 = res.body.tenant_hive
        }).catch(res => {
        })
      },
      getTableData(){

        let body = {};
        this.formInline.cOpts.map(item => {
          body[item.key] = item.val;
        });
        body.start_index = this.pagination.start_index;
        body.page_count = this.pagination.page_count;

        dao.getTablesList(body).then(res => {

          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false;
          }
          this.pagination.count = res.body.count || 0;
          this.tableData = res.body.tenant_hive;

        })

      },
      /*分页*/
      handleSizeChange (val) {
        this.pagination.page_count = val;
        this.getTableData();

      },
      /*分页点击*/
      handleCurrentChange (val) {

        this.pagination.start_index = val;
        this.getTableData();

      },
      /*字段详情数据*/
      getTableColumnsInfo(){
        let hive_database_name = this.multipleSelection[0].hive_database_name || ""
        let table = this.multipleSelection[0].table || ""
        dao.getTableColumnsInfo({hive_database_name, table}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false
          }
          this.$message('获取字段详情成功');
          this.fieldDetailsData = res.body.columns;
        })
      },
      /*分区详情数据*/
      getTablePartitionsInfo(){
        let hive_database_name = this.multipleSelection[0].hive_database_name || "";
        let table = this.multipleSelection[0].table || "";
        dao.getTablePartitionsInfo({hive_database_name, table}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false
          }
          this.$message('获取表分区信息成功');
          this.fqxqDetailsData = res.body.partitions;
        })
      },
      /*建表语句数据*/
      getTableCreateTable(){
        let hive_database_name = this.multipleSelection[0].hive_database_name || "";
        let table = this.multipleSelection[0].table || "";
        dao.getTableCreateTable({hive_database_name, table}).then(res => {
          if (!res.body || res.body.retCode != '200') {
            util.apiMsg(res);
            return false
          }
          this.$message('获取建表语句成功');
          this.jbyjDetailsData = res.body.createtablestr;
        })
      },
      /*新建表*/
      createTableByCreateStr () {
        this.$refs.form.validate((valid) => {

          if (!valid) {return false}
          let createtablestr = this.form.createtablestr;
          dao.createTableByCreateStr({createtablestr}).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false;
            }
            this.getTableData();
            this.dialogFormVisible = false;
            this.form.createtablestr = ''
            this.$message('创建表成功');
          })
        });
      },
      /*删除*/
      deleteTable () {
        if (this.multipleSelection.length < 1)return false
        this.$confirm('此操作将永久删除表, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let hive_database_name = this.multipleSelection[0].hive_database_name || "";
          let table = this.multipleSelection[0].table || "";
          dao.deleteTable({hive_database_name, table}).then(res => {
            if (!res.body || res.body.retCode != '200') {
              util.apiMsg(res);
              return false
            }
            this.getTableData();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      resetForm () { //重置表单
        if (this.dialogFormVisible) {
          this.$refs.form.resetFields();
          this.dialogFormVisible = false;
        } else if (this.dialogFormData) {
          this.$refs.formUp.resetFields();
          this.dialogFormData = false;
        }
      }
    },
    mounted () {
      this.getTableData();
    }
  }
</script>
<style scoped>
</style>